package com.qf.controller;

import com.qf.constant.AppConstant;
import com.qf.enums.AppEnum;
import com.qf.exception.AppException;
import com.qf.shiro.AppToken;
import com.qf.util.ResultVOUtil;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/backend/user")
@Slf4j
public class BackendUserController {


    //1. 跳转到登录页面
    @GetMapping("/login-ui")
    public String loginUI(){
        return "backend/user/login";
    }

    //用户登录
    @PostMapping("/login")
    @ResponseBody
    public ResultVO login(String backendCode, String backendPassword){
        if (StringUtils.isEmpty(backendCode)||StringUtils.isEmpty(backendPassword)){
            log.info("【用户注册】 登录时传入参数有误！用户名或密码不能为空");
            return ResultVOUtil.error(AppEnum.PARAM_ERROR.getCode(),"用户名或密码不能为空！");
        }
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new AppToken(backendCode,backendPassword, AppConstant.BACKEND_USER));
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            log.info("【用户登录】用户名错误！ username={} password={}",backendCode,backendPassword);
            throw new AppException(AppEnum.LOGIN_USERNAME_ERROR);
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            log.info("【用户登录】密码错误！ username={} password={}",backendCode,backendPassword);
            throw new AppException(AppEnum.LOGIN_PASSWORD_ERROR);
        }
        return ResultVOUtil.ok();
    }



}
